<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link rel="stylesheet" href="index.css"/>
	</head>
	<style>
		#draggable {
		  width: 400px;
		  height: 400px;
		  position: absolute;
		  cursor: pointer;
		  display: flex;
		}
	</style>
	<body>
		
		
		
		<div id="draggable">
			<div class="item1">
			
			</div>
			<div class="item2">
				
			</div>
			<div class="item3">
				
			</div>
		</div>
	</body>
	
	<script>
		
		// 获取可拖动的div元素
		// 获取可拖动的div元素
		var draggable = document.getElementById('draggable');
		var offsetX, offsetY;
		
		// 鼠标按下时记录鼠标相对于div左上角的偏移
		draggable.addEventListener('mousedown', function(e) {
		  e.preventDefault();
		  offsetX = e.clientX - draggable.getBoundingClientRect().left;
		  offsetY = e.clientY - draggable.getBoundingClientRect().top;
		
		  // 添加mousemove事件监听器
		  document.addEventListener('mousemove', dragElement);
		  
		  // 鼠标松开时移除mousemove事件监听器
		  document.addEventListener('mouseup', function() {
		    document.removeEventListener('mousemove', dragElement);
		  });
		});
		
		// 移动div元素的函数
		function dragElement(e) {
		  e.preventDefault();
		  let newX = e.clientX - offsetX;
		  let newY = e.clientY - offsetY;
		
		  // 边界检测，确保不超出屏幕可见区域
		  if (newX < 0) {
		    newX = 0;
		  }
		  if (newY < 0) {
		    newY = 0;
		  }
		  if (newX + draggable.offsetWidth > window.innerWidth) {
		    newX = window.innerWidth - draggable.offsetWidth;
		  }
		  if (newY + draggable.offsetHeight > window.innerHeight) {
		    newY = window.innerHeight - draggable.offsetHeight;
		  }
		
		  draggable.style.left = newX + 'px';
		  draggable.style.top = newY + 'px';
		}
	</script>
</html>